﻿using System;
using System.IO;
using DBCodeBuilder.CodeGeneration;
using DBCodeBuilder.Core.Enum;
using Newtonsoft.Json;

namespace DBCodeBuilder.Core.Classes
{
    public class SessionInfo
    {
        public static string ConfigDirPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\DbCodeBuilder\\UserConfig";
        private static string SettingsDirPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\DbCodeBuilder";
        private static string SettingsFilePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\DbCodeBuilder\\Settings.config";

        private static SessionInfo _instance;
        public string UserName;
        public Orm OrmCodeGeneration;
        public SaveMode FileSaveMode;
        public string SaveFolder;
        public bool GenerateDBMSOutput;
        public SaveAction SaveAction;
        public MapGenSettings MapGenSettings;

        public SessionInfo()
        {
            MapGenSettings = new MapGenSettings();
        }

        private void DefaultConfig()
        {
            GenerateDBMSOutput = false;
            OrmCodeGeneration = Orm.NHibernate;
            SaveAction = SaveAction.Overwrite;
            FileSaveMode = SaveMode.DistinctFile;
            SaveFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory) + "\\Code";
            MapGenSettings = new MapGenSettings
            {
                GenereteDomainEqualityComparer = false,
                GeneretePartialDomain = false,
            };
        }

        private static void LoadConfig()
        {
            _instance = JsonConvert.DeserializeObject<SessionInfo>(File.ReadAllText(SettingsFilePath));
        }

        private static void InitConfig()
        {
            _instance.DefaultConfig();
            SaveConfig();
        }

        public static void SaveConfig()
        {
            File.WriteAllText(SettingsFilePath, JsonConvert.SerializeObject(_instance));
        }

        public static SessionInfo Instance
        {
            get
            {
                if (_instance != null)
                    return _instance;

                _instance = new SessionInfo();

                if (!Directory.Exists(SettingsDirPath))
                    Directory.CreateDirectory(SettingsDirPath);

                if (!Directory.Exists(ConfigDirPath))
                    Directory.CreateDirectory(ConfigDirPath);

                if (!File.Exists(SettingsFilePath))
                    InitConfig();
                else
                    LoadConfig();

                return _instance;
            }
        }
    }
}